//
//  WbAuditManager.m
//  gdemm
//
//  Created by 乔明超 on 16/11/9.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "WbAuditManager.h"
#import "UrlInfo.h"
#import "FMDB.h"
#import <objc/runtime.h>
#import "PackageInfo.h"
#import "UserDefaultsUtil.h"
@interface WbAuditManager()
@property (assign,nonatomic) BOOL mBlackMode;
@property (strong,nonatomic) NSMutableArray *mWbAuditArr;
@property (assign,nonatomic) BOOL isUnInstall;
@property (assign,nonatomic) BOOL enable;
@end

@implementation WbAuditManager
static WbAuditManager *_mInstance;

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

//懒加载
- (NSMutableArray *)mWbAuditArr{
    if (_mWbAuditArr == nil) {
        _mWbAuditArr = [NSMutableArray array];
    }
    return _mWbAuditArr;
}
//创建单列
+ (instancetype)getInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mInstance = [[self alloc]init];
    });
    return _mInstance;
}

- (NSString *)supportPolicy{
    return WB_AUDIT;
}

- (BOOL)startPolicyWithPolicyType:(NSString *)policyType policyContent:(NSDictionary *)policyContent{
    
    _enable = YES;
    if (policyContent != nil) {
        [self parsePolicy:policyContent];
    }

    return true;

}

- (void)parsePolicy:(NSDictionary *)policyContent{
    
    //保存名单模式
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.cn.neiwang.gview"];
    NSString *mode = policyContent[@"mode"];
    [userDefaults setObject:mode forKey:@"mode"];
    
    //获取Gview浏览器的数据库路径
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSURL *url = [fileMgr containerURLForSecurityApplicationGroupIdentifier:@"group.cn.neiwang.gview"];
    NSString *path = [[url path] stringByAppendingPathComponent:@"profile.profile/browser.db"];

    NSArray *urlList = [UrlInfo urlInfoWithArray:policyContent[@"urlList"]];
    FMDatabase *db = [FMDatabase databaseWithPath:path];
    
    if ([db open]) {
        NSString *existsBlackList = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"blackList"];
        NSString *createBlackList = @"CREATE TABLE IF NOT EXISTS blackList(id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT NOT NULL,url TEXT UNIQUE )";
        FMResultSet *rs = [db executeQuery:existsBlackList];
        while ([rs next]) {
            NSInteger count = [rs intForColumn:@"countNum"];
            if (count == 1) {
                 [db executeUpdate:@"delete from blackList"];
                break;
            }
            [db executeUpdate:createBlackList];
        }
        
        NSString *existsWhiteList = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"whiteList"];
        NSString *createWhiteList = @"CREATE TABLE IF NOT EXISTS whiteList(id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT NOT NULL,url TEXT UNIQUE )";
        FMResultSet *whiteRs = [db executeQuery:existsWhiteList];
        while ([whiteRs next]) {
            NSInteger count = [rs intForColumn:@"countNum"];
            if (count == 1) {
                [db executeUpdate:@"delete from whiteList"];
                break;
            }
            [db executeUpdate:createWhiteList];
        }
        
        if ([mode isEqualToString:@"black"]) {
            for (UrlInfo *info in urlList) {
                [db executeUpdate:@"INSERT INTO blackList (title, url) VALUES (?,?);",info.title,info.url];
            }
        }else if([mode isEqualToString:@"white"]){
        
            for (UrlInfo *info in urlList) {
                [db executeUpdate:@"INSERT INTO whiteList (title, url) VALUES (?,?);",info.title,info.url];
            }
        }
        
    }

}

- (BOOL)stopPolicyWithPolicyType:(NSString *)policyType{

    //取消策略
    _enable = NO;
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.cn.neiwang.gview"];
    [userDefaults setObject:nil forKey:@"mode"];
    
    return NO;
}

- (BOOL)valid{
    return _enable;
}

- (void)run{
    
    _isUnInstall = YES;
    NSArray *installInfo = [self getAllAppsFromDevice];
    for (PackageInfo *info in installInfo ) {
        if ([info.packageName isEqualToString:@"cn.neiwang.gview"]) {
            _isUnInstall = NO;
        }
    }
    if (_isUnInstall) {
        if ([[UserDefaultsUtil shareInstance]getString:LC_SERVADDR] != nil) {
            
            if ([self checkGviewIsInstalling]) {
                return;
            }
            NSString *path = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://%@/Resource/MdmApk/Fennec.plist",[[UserDefaultsUtil shareInstance]getString:LC_SERVADDR]];
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:path]];
        }
        
    }

}

//获取用户安装的app信息
- (NSMutableArray *)getAllAppsFromDevice
{
    
    NSMutableArray *app = [NSMutableArray array];
    //获取手机上所有的app
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    NSArray *apps = [workspace performSelector:@selector(allInstalledApplications)];
    Class LSApplicationProxy_class = objc_getClass("LSApplicationProxy");
    for (int i = 0; i < apps.count; i++) {
        NSObject *temp = apps[i];
        if ([temp isKindOfClass:LSApplicationProxy_class]) {
            NSString *appBundleId = [temp performSelector:NSSelectorFromString(@"applicationIdentifier")];
            NSString *appName = [temp performSelector:NSSelectorFromString(@"localizedName")];
            
            NSString * type = [temp performSelector:NSSelectorFromString(@"applicationType")];
            
            if ([type isEqualToString:@"User"]) {
                PackageInfo *packageInfo = [[PackageInfo alloc]init];
                packageInfo.softName = appName;
                packageInfo.packageName = appBundleId;
                [app addObject:packageInfo];
            }
            
        }
    }
    return app;
}

//检测应用是否正在安装
- (BOOL)checkGviewIsInstalling{

    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    NSArray *apps = [workspace performSelector:@selector(placeholderApplications)];
    Class LSApplicationProxy_class = objc_getClass("LSApplicationProxy");
    for (int i = 0; i < apps.count; i++) {
        NSObject *temp = apps[i];
        if ([temp isKindOfClass:LSApplicationProxy_class]) {
            NSString *appBundleId = [temp performSelector:NSSelectorFromString(@"applicationIdentifier")];
            
            if ([appBundleId isEqualToString:@"cn.neiwang.gview"]) {
                return YES;
            }
        }
    }
    
    return NO;
}

@end
